package com.example.cardgame

import android.animation.ObjectAnimator
import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.cardgame.model.Card
import com.example.cardgame.model.CardMatchingGame

class CardAdapter(private val game: CardMatchingGame) :
    RecyclerView.Adapter<CardAdapter.ViewHolder>() {

    private var listener: ((Int) -> Unit)? = null

    fun setOnClickListener(l: (Int) -> Unit) {
        listener = l
    }

    inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val textView: TextView = view.findViewById(R.id.card_text)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.item_layout, parent, false)
        return ViewHolder(view)
    }

    override fun getItemCount(): Int = game.cards.size

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val card = game.cards[position]

        // 设置显示内容：选中显示牌面，否则显示背面
        if (card.isChosen || card.isMatched) {
            holder.textView.text = card.toString()
            holder.textView.setBackgroundColor(Color.parseColor("#FFF59D")) // 亮黄色背景
            holder.textView.setTextColor(Color.BLACK)
        } else {
            holder.textView.text = "?" // 背面
            holder.textView.setBackgroundColor(Color.parseColor("#4CAF50")) // 绿色背面
            holder.textView.setTextColor(Color.WHITE)
        }

        // 已匹配的卡设为灰色
        if (card.isMatched) {
            holder.textView.setBackgroundColor(Color.LTGRAY)
        }

        // 点击事件
        holder.textView.setOnClickListener {
            // 禁止点击已匹配的卡
            if (!card.isMatched) {
                listener?.invoke(position)
                flipAnimation(holder.textView)
            }
        }
    }

    // ✅ 点击时添加一个轻微翻转动画
    private fun flipAnimation(view: View) {
        val flip = ObjectAnimator.ofFloat(view, "rotationY", 0f, 180f)
        flip.duration = 300
        flip.start()
    }
}
